﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class admin_search : System.Web.UI.Page
{
    DataSet ds = null, dst=null;
    rUser ruser=null;
    public long RSearch = 0, PSearch = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null) { Response.Redirect("../Default.aspx"); }
        
        ruser = (rUser)(Session["userinfo"]);
        if (ruser != null)
        {
            RE_GenericBean permit = new RE_GenericBean();
            permit = Utility.getPermisobyRuser(ruser, 5);
            PSearch = permit.int64C1;
            RSearch = permit.int64C2;
        }

        //Si es la primera vez que entra
        if (!Page.IsPostBack)
        {
            fillCompanies();
            fillAccounts();
            fillProducts();
            fillclients("");
            fillsector();
            cb_processor.Items.Clear();
            cb_driver.Items.Clear();
            cb_driverlog.Items.Clear();
            cb_qc.Items.Clear();
            cb_processor.Items.Add("Select One");
            cb_driver.Items.Add("Select One");
            cb_driverlog.Items.Add("Select One");
            cb_qc.Items.Add("Select One");
            Utility.fillAgent("", 3, 2, cb_processor);
            Utility.fillAgent("", 7, 2, cb_processor);
            Utility.fillAgent("", 10, 2, cb_processor);
            Utility.fillAgent("", 13, 2, cb_processor);
            Utility.fillAgent("", 1, 1, cb_driver);
            Utility.fillAgent("", 1, 1, cb_driverlog);
            Utility.fillAgent("", 7, 1, cb_qc);
            Utility.fillAgent("", 10, 1, cb_qc);
            ListItem other1 = new ListItem();
            other1.Text = "Other"; other1.Value = "OT";
            cb_driver.Items.Add(other1);
            cb_driver.Items[cb_driver.Items.Count - 1].Attributes.Add("disabled", "true");
            ListItem fs1 = new ListItem();
            fs1.Text = "FS Team";
            fs1.Value = "FST";
            cb_driver.Items.Add(fs1);
            ListItem other = new ListItem();
            other.Text = "Other"; other.Value = "OT";
            cb_driverlog.Items.Add(other);
            cb_driverlog.Items[cb_driverlog.Items.Count - 1].Attributes.Add("disabled", "true");
            ListItem fs = new ListItem();
            fs.Text = "FS Team";
            fs.Value = "FST";
            cb_driverlog.Items.Add(fs);
            cb_ssubmitted.SelectedIndex = 0;
            cb_msubmitted.SelectedIndex = 0;
            cb_sumitted.SelectedIndex = 1;
            cb_sumittedlog.SelectedIndex = 1;
       
            restricted();
            permiso();
           
           
        }
        else { ruser = (rUser)(Session["userinfo"]); }
        
    }

    private void fillCompanies()
    {
        try
        {
            DataSet dsc = (DataSet)(Session["companies"]);
            if (dsc != null)
            {
                ListItem listitem0 = new ListItem();
                listitem0.Text = "All"; listitem0.Value = "All";
                cb_company.Items.Add(listitem0);
                cb_companylog.Items.Add(listitem0);
                for (int ii = 0; ii <= (dsc.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsc.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsc.Tables[0].Rows[ii][0].ToString();
                    cb_company.Items.Add(listitem);
                    cb_companylog.Items.Add(listitem);
                }

            }

        }
        catch (Exception ec)
        {
            Utility.writeError("WS getCompanies no devolvio companias " + ec.Message);
        }
    }

    private void fillAccounts()
    {
        try
        {
            DataSet dsc = (DataSet)(Session["accounts"]);
            if (dsc != null)
            {
                ListItem listitem0 = new ListItem();
                listitem0.Text = "All"; listitem0.Value = "All";
                cb_account.Items.Add(listitem0);

                for (int ii = 0; ii <= (dsc.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsc.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsc.Tables[0].Rows[ii][0].ToString();
                    cb_account.Items.Add(listitem);
                }

            }

        }
        catch (Exception ec)
        {
            Utility.writeError("WS getCompanies no devolvio companias " + ec.Message);
        }
    }

    private void fillProducts()
    {

        DataSet products = DB.GetProducts();
        if (products != null)
        {
            ListItem li = new ListItem();
            li.Text = "All"; li.Value = "All";
            cb_type.Items.Add(li);
            for (int i = 0; i <= (products.Tables[0].Rows.Count - 1); i++)
            {
                if (!products.Tables[0].Rows[i][0].ToString().ToUpper().Equals("0"))
                {
                    li = new ListItem();
                    li.Text = products.Tables[0].Rows[i]["Initial"].ToString();
                    li.Value = products.Tables[0].Rows[i][0].ToString();
                    cb_type.Items.Add(li);
                }

            }
        }
    }

    private void fillCounties(int sector)
    {
        cb_county.Items.Clear();
      
      //  DataSet counties = DB.getAllCounties();
        DataSet counties = DB.getCountiesbySector( sector);
        if (counties != null)
        {
            ListItem li = new ListItem();
            li.Text = "All"; li.Value = "All";
            cb_county.Items.Add(li);
           
            for (int i = 0; i <= (counties.Tables[0].Rows.Count - 1); i++)
            {
                if (!counties.Tables[0].Rows[i][3].ToString().ToUpper().Equals("0"))
                {
                    li = new ListItem();
                    li.Text = counties.Tables[0].Rows[i]["Name"].ToString();
                    li.Value = counties.Tables[0].Rows[i]["initial"].ToString();
                    cb_county.Items.Add(li);
                  
                }

            }
        }
    }
    private void fillCountieslog(int sector)
    {
       
        cb_countylog.Items.Clear();
        //  DataSet counties = DB.getAllCounties();
        DataSet counties = DB.getCountiesbySector(sector);
        if (counties != null)
        {
            ListItem li = new ListItem();
            li.Text = "All"; li.Value = "All";
           
            cb_countylog.Items.Add(li);
            for (int i = 0; i <= (counties.Tables[0].Rows.Count - 1); i++)
            {
                if (!counties.Tables[0].Rows[i][3].ToString().ToUpper().Equals("0"))
                {
                    li = new ListItem();
                    li.Text = counties.Tables[0].Rows[i]["Name"].ToString();
                    li.Value = counties.Tables[0].Rows[i]["initial"].ToString();
                    
                    cb_countylog.Items.Add(li);
                }

            }
        }
    }

    private void fillclients(string client)
    {
        try
        {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.UsuariosPorPerfil(1);

            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getUsuariosporPerfil(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "All"; listitem0.Value = "All";
                cb_client.Items.Add(listitem0);
                cb_clientlog.Items.Add(listitem0);

                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][2].ToString() + " " + dsclient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cb_client.Items.Add(listitem);
                    cb_clientlog.Items.Add(listitem);
                    //if (ii == 5) { cb_client.SelectedIndex = ii; }
                    if (client.Equals(dsclient.Tables[0].Rows[ii][0].ToString()))
                    {
                        cb_client.SelectedValue = dsclient.Tables[0].Rows[ii][0].ToString();
                        cb_clientlog.SelectedValue = dsclient.Tables[0].Rows[ii][0].ToString();
                    }
                }
            }

        }
        catch (Exception ee)
        {
            Utility.writeError(ee.Message);
        }
    }

    

    protected void fillsector()
    {
        cb_sector.Items.Clear();
        cb_sectorlog.Items.Clear();

        DataSet ds = DB.getSectors();
        if (ds != null)
        {
            cb_sector.Items.Add("All");
            cb_sectorlog.Items.Add("All");
            for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
            {
                if (ds.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                {
                    ListItem Li = new ListItem();
                    Li.Value = ds.Tables[0].Rows[i]["sector_id"].ToString();
                    Li.Text = ds.Tables[0].Rows[i]["name"].ToString().ToUpper();
                    cb_sector.Items.Add(Li);
                    cb_sectorlog.Items.Add(Li);



                }
            }
        }
    }
    protected void cb_pics_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    

    public void restricted()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
            //permiso = long.Parse(user.getRestricted().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 5);
            permiso = permi.int64C2;
        }
        if ((permiso & 1) == 1) { Response.Redirect(Request.UrlReferrer.ToString()); }
        // Acceso a Logistic Search
        if ((permiso & 2) == 2) { PlogisticSearch.Visible=false; }
        // Acceso a  Accounting
        //if ((permiso & 4) == 4) { PAcc.Visible = false; }
        
        //Response.Redirect(Request.ServerVariables("HTTP_REFERER"));
    }

    public void permiso()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
            //permiso = long.Parse(user.getPermisoUser().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 5);
            permiso = permi.int64C1;
        }
        if ((PSearch & 2) != 2) { PlogisticSearch.Enabled = false; }
        //if ((PSearch & 4) != 4) { PAcc.Enabled = false; }
        if ((PSearch & 8) != 8) { Panel3.Enabled = false; }
        if ((PSearch & 16) != 16) { Psearch.Enabled = false; }
        if ((permiso & 1) != 1) { Panel2.Enabled = false; Panel3.Enabled = false; Psearch.Enabled = false; PlogisticSearch.Enabled = false; }
    }

    protected void lnk_searchsin_Click(object sender, EventArgs e)
    {
        if (tb_order.Text != "")
        {
            tb_order.Text = tb_order.Text.Trim();
        }
        string message = "";
        if (!tb_order.Text.Equals("") || (!tb_stnum.Text.Equals("")))
        {


            string where1 = "";
            if (!tb_stnum.Text.Equals(""))
            {
                where1 = " and orden.stnum like '" + tb_stnum.Text + "'";
                message = " **** Address " + tb_stnum.Text;
            }
            if (!cb_ssubmitted.SelectedValue.Equals("All"))
            {

               
                if (cb_ssubmitted.SelectedValue.ToUpper().Equals("NO"))
                {
                    where1 = where1 + " and (orden.ord_submit = 'NO' or orden.ord_submit is null )";
                }
                else
                {
                    where1 = where1 + " and orden.ord_submit = 'YES'";
                }

            }


            if (!tb_order.Text.Equals(""))
            {// si tiene numero de orden a buscar
                where1 = where1 + " and orden.ordernum= '" + tb_order.Text + "'";
                if (!message.Equals("")) { message = message + " and  "; } else { message = " ***** "; }
                message = message + " Order "+ tb_order.Text; 
            }

            Session["wheress"] = where1;
            Session["SingleSearch"] = 1;
            Session["message"]= message + " not Found **** ";
            Response.Redirect("WorkSpace.aspx");

        }
    }
    protected void lnk_searchmul_Click(object sender, EventArgs e)
    {
        string ordersgroup = tb_orders.Text.Trim();

        ordersgroup = ordersgroup.Replace(",", "','");
        ordersgroup = "'" + ordersgroup + "'";
        ordersgroup = "and orden.ordernum in (" + ordersgroup + ")";
        if (!cb_msubmitted.SelectedValue.Equals("All"))
        {

            if (cb_msubmitted.SelectedValue.ToUpper().Equals("NO"))
            {
                ordersgroup = ordersgroup + " and (orden.ord_submit = 'NO' or orden.ord_submit is null )";
            }
            else
            {
                ordersgroup = ordersgroup + " and orden.ord_submit = 'YES'";
            }

        }
        Session["masivo"] = ordersgroup;
        Response.Redirect("WorkSpace.aspx");
      
    }

    protected void lnk_searchfil_Click(object sender, EventArgs e)
    {
        
       
        try
        {
            string where = "";
           

            if (!cb_client.SelectedValue.Equals("All"))
                where = where + " and orden.client_id='" + cb_client.SelectedValue + "'";

            if (!cb_company.SelectedValue.Equals("All"))
                where = where + " and orden.company = " + cb_company.SelectedValue;

            if (!cb_account.SelectedValue.Trim().Equals("All"))
                where = where + " and  orden.account = " + cb_account.SelectedValue;

            if ( cb_county.Enabled== true && !cb_county.SelectedValue.Equals("All"))
                where += " and orden.county='" + cb_county.SelectedValue.ToUpper() + "'";

            if (!cb_type.SelectedValue.Equals("All"))
                where = where + " and orden.product='" + cb_type.SelectedItem.ToString().ToUpper() + "'";

            if (!cb_sumitted.SelectedValue.Equals("All"))
            {
                if (cb_sumitted.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_submit = 'NO' or orden.ord_submit is null ) and (UPPER(orden.status)= 'PENDING') ";
                }
                else
                {
                    where = where + " and orden.ord_submit = 'YES'";
                }



            }
            if (!cb_pics.SelectedValue.Equals("All"))
            {
                if (cb_pics.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_driver_done='NO' or orden.ord_driver_done is null) ";
                }
                else
                {
                    where = where + " and (orden.ord_driver_done='YES') ";
                }


            }

            if (!cb_completed.SelectedValue.Equals("All"))
            {
                if (cb_completed.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_processor_done='NO' or orden.ord_processor_done is null) ";
                }
                else
                {
                    where = where + " and (orden.ord_processor_done='YES') ";
                }
            }

            if (!cb_qcdone.SelectedValue.Equals("All"))
            {
                if (cb_qcdone.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_qc_done='NO' or orden.ord_qc_done is null) ";
                }
                else
                {
                    where = where + " and (orden.ord_qc_done='YES') ";
                }

            }
          



            if (!cb_failed.SelectedValue.Equals("All"))
            {
                if (cb_failed.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_failed='NO' or orden.ord_failed is null ) ";
                }
                else
                {
                    where = where + " and (orden.ord_failed='YES' ) ";
                }
            }

            /*if ((tb_stardate.Text != null) && (!tb_stardate.Text.Equals("")))
            {
                String[] fecha = tb_stardate.Text.Split('/');
                where = where + " and orden.duedate>='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }


            if ((tb_enddate.Text != null) && (!tb_enddate.Text.Equals("")))
            {
                String[] fecha2 = tb_enddate.Text.Split('/');
                where = where + " and orden.duedate<='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            */
            if (!(cb_processor.SelectedValue.Equals("Select One")) && (!cb_processor.SelectedValue.Equals("Processors")))
                where = where + " and orden.ord_processor='" + cb_processor.Text.Trim().ToUpper() + "'";


            if ((!cb_driver.SelectedValue.Equals("Select One")) && (!cb_driver.SelectedItem.Equals("Driver")))
                where = where + " and orden.ord_driver='" + cb_driver.Text.Trim().ToUpper() + "'";

            if (!cb_qc.SelectedValue.Equals("Select One") && (!cb_qc.SelectedValue.Equals("Processors")))
                where = where + " and orden.ord_qc = '" + cb_qc.SelectedValue.ToUpper() + "' ";

            if (!cb_sector.SelectedValue.Equals("All"))
            {

                where = where + " and (orden.ord_sector= " + cb_sector.SelectedValue.ToString() + " ) ";


            }

         
            Session["where"] = where;
            Session["FilterSearch"] = 1;
            Response.Redirect("WorkSpace.aspx");
        }
        catch {
            Response.Write("<script> alert('Invalid criteria for Search');</script>");
        }
    }
    protected void lnk_logisticsearh_Click(object sender, EventArgs e)
    {
        Session["where"] = busquedaLogistic();
        Session["FilterSearch"] = 1;
        Response.Redirect("WorkSpace.aspx");
        
    }

    protected string busquedaLogistic() {
        string where = "";
        try
        {
           
            /*if ((tb_street.Text != null) && (!tb_street.Text.Equals("")))
               where = where + " and stnum='" + tb_street.Text.Trim().ToUpper() + "'";
            if ((tbStreet.Text != null) && (!tbStreet.Text.Equals("")))
                where = where + " and ord_street_number='" + tbStreet.Text.Trim() + "'";*/

            if (!cb_clientlog.SelectedValue.Equals("All"))
                where = where + " and orden.client_id='" + cb_clientlog.SelectedValue + "'";

            if (!cb_companylog.SelectedValue.Equals("All"))
                where = where + " and orden.company = " + cb_companylog.SelectedValue;


            if (cb_countylog.Enabled == true && !cb_countylog.SelectedValue.Equals("All"))
                where += " and orden.county='" + cb_countylog.SelectedValue.ToUpper() + "'";



            if (!cb_sumittedlog.SelectedValue.Equals("All"))
            {
                if (cb_sumittedlog.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_submit = 'NO' or orden.ord_submit is null )  and (UPPER(orden.status)= 'PENDING') ";
                }
                else
                {
                    where = where + " and orden.ord_submit = 'YES'";
                }



            }
            if (!cb_picslog.SelectedValue.Equals("All"))
            {
                if (cb_picslog.SelectedValue.ToUpper().Equals("NO"))
                {
                    where = where + " and (orden.ord_driver_done='NO' or orden.ord_driver_done is null) ";
                }
                else
                {
                    where = where + " and (orden.ord_driver_done='YES') ";
                }


            }


            if (!cb_sectorlog.SelectedValue.Equals("All"))
            {

                where = where + " and (orden.ord_sector= " + cb_sectorlog.SelectedValue.ToString() + " ) ";


            }



            if ((!cb_driverlog.SelectedValue.Equals("Select One")) && (!cb_driverlog.SelectedItem.Equals("Driver")))
                where = where + " and orden.ord_driver='" + cb_driverlog.Text.Trim().ToUpper() + "'";



            //para reporttype
            if (cb_reporttypelog.SelectedValue.ToUpper().Equals("INTERIOR"))
            {

                where = where + " and (orden.product= 'INT' or orden.product = 'IPICS' or orden.product = 'PCRI') ";

                if (!txtdateint0.Text.Equals(""))
                {
                    String[] fechaint = txtdateint0.Text.Split('/');
                    where = where + " and (orden.appdate ='" + fechaint[0] + "/" + fechaint[1] + "/" + fechaint[2] + "')";
                }

            }
            else if ((cb_reporttypelog.SelectedValue.ToUpper().Equals("EXTERIOR")))
            {
                where = where + " and (orden.product= 'DB' or orden.product = 'EPICS' or orden.product = 'PCR' ) ";
                if (!txtdateint0.Text.Equals(""))
                {
                    String[] fechaint = txtdateint0.Text.Split('/');
                    where = where + " and (orden.appdate ='" + fechaint[0] + "/" + fechaint[1] + "/" + fechaint[2] + "')";
                }
            }


           
        }
        catch
        {
            Response.Write("<script> alert('Invalid criteria for Search');</script>");
        }
        return where;
    }

    protected void cb_sector_SelectedIndexChanged(object sender, EventArgs e)
    {
        fillCounties(int.Parse(cb_sector.SelectedValue.ToString()));
        cb_county.Enabled = true;
    }
    protected void cb_sectorlog_SelectedIndexChanged(object sender, EventArgs e)
    {
        fillCountieslog(int.Parse(cb_sectorlog.SelectedValue.ToString()));
        cb_countylog.Enabled = true;
    }

    protected void lnk_logisticAssign_Click(object sender, EventArgs e)
    {

        Session["where"] = busquedaLogistic();
        Response.Redirect("Assignment.aspx");

    }
}